import axios from 'axios'
import Vue from 'vue'
import { Toast } from 'vant'
import config from './config'
import router from '../router'
import store from '../store'
import showMarkUrl from './showMarkUrl'

Vue.use(Toast)
Toast.allowMultiple();

const service = axios.create({
  baseURL:config.baseUrl,
  timeout:10000
})

let markArr = []
let timeOut = null

axios.defaults.withCredentials = true// 携带cookie

service.interceptors.request.use(
  config=>{
    let f = showMarkUrl.find(e=>e == config.url)
    if(f){
      let obj = {
        url:f,
        toast:Toast.loading({
          duration:0,
          forbidClick:true,
          message: '加载中...',
        })
      }
      markArr.push(obj)
    }
    if(store.state.user.userInfo){
      config.headers['Authori-zation'] = '' + store.state.user.userInfo.token
    }
    if(config.url.indexOf("/home/upload") != -1){
      config.baseURL = ""
      config.headers["Content-Type"] = "multipart/form-data; boundary=----WebKitFormBoundarynSNG6LEmhcnVagKq"
    }
    return config
  },
  error=>{
    return error
  }
)

service.interceptors.response.use(
  response=>{
    return new Promise((resolve, reject) => {
      clearTimeout(timeOut)
      let idx = markArr.findIndex(e=>e.url == response.config.url)
      // console.log("response",markArr[idx])
      if(idx != -1){
        markArr[idx].toast.clear()
        markArr.splice(idx,1)
      }
      timeOut = setTimeout(()=>{
        Toast.clear()
      },4000)
      let errcode = response.data?response.data.errcode:0
      switch(errcode){
        case 0:
        case "0":
        case "1000":
          resolve(response.data)
        break;
        case "40002":
          Toast.fail(response.data.errmsg)
          router.push(config.routerUrl+"/register")
        break;
        case "40001":
        case "40004":
        case "40009":
          Toast.fail(response.data.errmsg)
          store.commit("user/outLogin")
        break;
        case "40013":
          Toast.fail(response.data.errmsg)
          router.push(config.routerUrl+"/*")
        break;
        case "40012": // 已停场
          reject(response.data)
        break;
        case "40010":
        case "10001": //短信验证错误码
        case "40003": 
        case "40006":
        case "40007":
        case "40008":
        case "40011": // 参数错误
        case "40015":
        case "40017":
          Toast.fail(response.data.errmsg)
          reject(response.data)
        break;
        default:
          let msg = response.data.errmsg?response.data.errmsg:"请求失败"
          Toast.fail(msg)
          reject(response.data)
        break;
      }
    });
  },
  error=>{
    // console.log(error)
    Toast.clear()
    Toast.fail("请求错误")
  }
)

class api
{
  static get(path,params){
    return new Promise((resolve, reject) => {
      service({
        url:path,
        method:'GET',
        params
      }).then(e=>{
        resolve(e)
      }).catch(err=>{
        reject(err)
      })
    });
  }

  static post(path,params){
    return new Promise((resolve, reject) => {
      let data = null
      if(path.indexOf("/home/upload") != -1){ //上传接口时修改
        data = new FormData()
        data.append("file",params["file"])
      }else{
        data = new URLSearchParams()
        for(let i in params){
          data.append(i,params[i])
        }
      }
      service({
        url:path,
        method:'POST',
        data
      }).then(e=>{
        resolve(e)
      }).catch(err=>{
        reject(err)
      })
    });
  } 
}

export default api